import {
  HTTP_REQUEST_URL,
  HEADER,
  TOKENNAME,
  HEADERPARAMS,
  TOKENPPREFIX
} from '@/config/index.js';
import store from '../store';

/**
 * 发送请求
 */
function baseRequest(url, method, data, {
  noAuth = false,
  noVerify = false
}, params) {
  let Url = HTTP_REQUEST_URL,
    header = HEADER
  if (params != undefined) {
    header = HEADERPARAMS;
  }
  if (!noAuth) {
    //登录过期自动登录
    if (!store.state.token) {
      toLogin();
      return Promise.reject('');
    }
  }
  if (store.state.token) header[TOKENNAME] = TOKENPPREFIX + store.state.token;
  return new Promise((reslove, reject) => {
    uni.request({
      url: Url + url,
      method: method || 'GET',
      header: header,
      data: data || {},
      success: (res) => {
        console.log("code", res.data);
        if (noVerify)
          reslove(res.data, res);
        else if (res.data.code == 10000)
          reslove(res.data, res);
        else if ([10006, 10001, 10004, 10007, 10008].indexOf(res.data.code) !== -1) {
          store.commit("saveToken", "")
          toLogin();
          reject(res.data);
        } else
          reject(res.data.message || '系统错误');
      },
      fail: (msg) => {
        reject(msg);
      }
    })
  });
};

function toLogin() {
  uni.navigateTo({
    url: '/pages/login/index'
  })
};

const request = {};

['options', 'get', 'post', 'put', 'head', 'delete', 'trace', 'connect'].forEach((method) => {
  request[method] = (api, data, opt, params) => baseRequest(api, method, data, opt || {}, params)
});



export default request;